package com.blog.cloud.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class ProducerService {

    private final RocketMQTemplate rocketMQTemplate;

    // 异步发送
    public void asyncSend(String message) {
        String namesrvAddr = rocketMQTemplate.getProducer().getNamesrvAddr();
        log.info("Producing message " + message);
        Message<String> msg = MessageBuilder.withPayload(message).build();
        rocketMQTemplate.asyncSend("rocket-topic", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送失败");
            }
        });
    }

    // 同步发送
    public void send(String message) {
        log.info("send发送消息:{}", message);
        rocketMQTemplate.send("rocket-topic",
                MessageBuilder.withPayload("Hello World").build());
    }

    // 转换并发送
    public void convertAndSend(String message) {
        log.info("convertAndSend发送消息:{}", message);
        rocketMQTemplate.convertAndSend("rocket-topic", message);
    }

}
